//
//  UserBase2ViewController.swift
//  jiaoyi
//
//  Created by wjk on 2018/8/9.
//  Copyright © 2018年 wjk. All rights reserved.
//

import UIKit
import PGDatePicker
import SwiftyJSON

typealias changeUserBlock = (([String:String]) -> ())

class UserBase2ViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource {

    var datas = [[["title":"企业名称","subTitle":"必填","isRequird":true,"key":"","value":"","type":0]]]
    
    var ca_status:String = "1"
    
    
    var unclickKeys = ["name","type","biz_license_type","biz_license_no","user_name","user_phone","user_identity_card"]
    
    
   var data1 = [["title":"注册资金","subTitle":"万元","isRequird":true,"key":"registered_capital","value":"","type":0],
    ["title":"税务证编号","subTitle":"请填写","isRequird":true,"key":"tax_cert_no","value":"","type":0],
    ["title":"税务证附件","subTitle":"未上传","isRequird":true,"key":"tax_cert_atta","value":"","type":4],
    ["title":"组织机构代码","subTitle":"请填写","isRequird":true,"key":"org_code","value":"","type":0],
    ["title":"组织机构代码附件","subTitle":"未上传","isRequird":true,"key":"org_code_atta","value":"","type":4],
    ["title":"加工许可证号","subTitle":"请填写","isRequird":true,"key":"processing_license_no","value":"","type":0],
    ["title":"加工许可证附件","subTitle":"未上传","isRequird":true,"key":"processing_license_atta","value":"","type":4],
    ["title":"收购许可证","subTitle":"请填写","isRequird":false,"key":"purchase_license_no","value":"","type":0],
    ["title":"收购许可证附件","subTitle":"未上传","isRequird":false,"key":"purchase_license_atta","value":"","type":4],
    ]
    
    var data2 = [["title":"注册资金","subTitle":"万元","isRequird":true,"key":"registered_capital","value":"","type":0],
                 ["title":"加工许可证号","subTitle":"请填写","isRequird":true,"key":"processing_license_no","value":"","type":0],
                 ["title":"加工许可证附件","subTitle":"未上传","isRequird":true,"key":"processing_license_atta","value":"","type":4],
                 ["title":"收购许可证","subTitle":"请填写","isRequird":false,"key":"purchase_license_no","value":"","type":0],
                 ["title":"收购许可证附件","subTitle":"未上传","isRequird":false,"key":"purchase_license_atta","value":"","type":4],
                 ]
    
    
    var business_types1:[String] = ["小麦粉加工企业","大米加工企业","杂粮及薯类加工企业","食用植物油加工企业","饲料企业","会员经营类型","养殖企业","食品及副食酿造企业","食用酒精加工","酒精企业","制酒企业","淀粉企业","粮油机械制造企业","工业酒精加工"]//,"粮油批发市场","贸易企业"
    var business_types2:[String] = ["收储企业"]

    var types:[String] = ["企业性质为","国有企业","国有控股企业","外资企业","合资企业","私营企业","物流","个体工商企业"]
    
    //其中，type为1、输入框，1、选择框，2、多选点击框，3、身份证，4、单图上传
    
    var type:Int = 0
    
    var noEdit:Bool = false
    
    var dicts:[Any] = [Any]()
    
    var dates:String = ""
    
    var city1:[JSON] = [JSON]()
    var city2:[JSON] = [JSON]()
    var city3:[JSON] = [JSON]()
    
    
    
    lazy var cityPicker:TTADataPickerView = {
        let pickerView = TTADataPickerView(title: "选择", type: .text, delegate: nil)
        pickerView.type = .text
//        pickerView.show()
        return pickerView
    }()
    
    
    @IBOutlet weak var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.register(R.nib.userBase2TableViewCell(), forCellReuseIdentifier: "UserBase2TableViewCell")
        tableView.rowHeight = 46;
         self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "保存", style: .plain, target: self, action: #selector(self.save(_:)))
        loadData()
        loadCity1()
       
        
        // Do any additional setup after loading the view.
    }
    
    @objc func save(_ bar : UIBarButtonItem) {
        
        var param = [String:Any]()
        
        
        
        datas.forEach { (d1) in
            d1.forEach({ (d) in
                
                let keys = (d["key"] as! String).split(separator: ",")
                
                
                let real = d["value"] as? String
                
                if real?.isEmpty == false {
                    let values = (d["value"] as! String).split(separator: ",")
                    
                    for i in 0 ..< keys.count {
                        if i < values.count && values[i].isEmpty == false {
                            if keys[i] == "bank_attachments" || keys[i] == "business_type" {
                                
                                if keys[i] == "business_type" {
                                
                                    self.dicts.forEach({ (dic) in
                                        
                                        let jd2 = jsonFormater(data: dic)
                                        
                                        if jd2["key"].stringValue == "biz_type" {
                                            jd2["value"].arrayValue.forEach({ (js) in
                                                
                                                for j in 0 ..< values.count {
                                                    if js["name"].stringValue == values[j] {
                                                        param["\(keys[i])[\(j)]"] = js["code"].stringValue
                                                    }
                                                }
                                                
                                            })
                                        }
                                        
                                    })
                                }else {
                                
                                    for j in 0 ..< values.count {
                                        param["\(keys[i])[\(j)]"] = values[j]
                                    }
                                }
                                
                            }else {
                                param["\(keys[i])"] = values[i]
                            }
                        }
                    }
                }
            })
        }
        
        showHUD()
        if self.type == 0 { // 个人代表
            param["ca_status"] = ca_status
            NetWorkRequest(.userinfopost(param: param)) { (res) -> (Void) in
                if res["code"] as! String == "000000" {
                    showMessage(message: "保存成功")
                    (UIApplication.shared.delegate as! AppDelegate).enterprise_name = jsonFormater(data: param)["name"].stringValue
                    self.navigationController?.popViewController(animated: true)
                }
            }
        }else if self.type == 1 { // 交易代表
            NetWorkRequest(.daibiaopost(param: param)) { (res) -> (Void) in
                if res["code"] as! String == "000000" {
                    showMessage(message: "保存成功")
                    self.navigationController?.popViewController(animated: true)
                }
            }
        }else {//银行账号信息
            NetWorkRequest(.bankaccountpost(param: param)) { (res) -> (Void) in
                if res["code"] as! String == "000000" {
                    showMessage(message: "保存成功")
                    self.navigationController?.popViewController(animated: true)
                }
            }
        }
    }
    
    func loadData() -> Void {
        
        
        var param = [String:String]()
        
        if self.type == 0 { // 个人代表
            NetWorkRequest(.userinfoget()) { (res) -> (Void) in                
                if res["code"] as! String == "000000" {
                    let jd = jsonFormater(data: res["data"] as Any)
                    self.dicts = (jd["dicts"].arrayObject)!
                    if jd["items"].dictionaryValue.isEmpty == false {
                        
                        
                        
                        let items = jd["items"].dictionaryValue//取出这里的对象
                        
                        self.noEdit = true
                        let enterprise = items["enterprise"]!.dictionaryValue//企业信息
                        param["name"] = enterprise["name"]?.stringValue
                        param["alias"] = enterprise["alias"]?.stringValue
                        param["type"] = "\(enterprise["type"]!.stringValue)&\(enterprise["type_name"]!.stringValue)"
                        
                        param["business_type"] = enterprise["biz_type_name"]?.stringValue//显示的value为文字，上传的时候，转换为code,
                        
                        param["corporate"] = enterprise["corporate"]?.stringValue
                        param["identity_card"] = enterprise["identity_card"]?.stringValue
                        
                        param["valid_doc_a_atta,valid_doc_b_atta"] = "\(enterprise["identity_a_attachment"]!.dictionaryValue["attachment_token"]!.stringValue),\(enterprise["identity_b_attachment"]!.dictionaryValue["attachment_token"]!.stringValue)"
                        
                        param["phone"] = enterprise["phone"]?.stringValue
                        param["landline"] = enterprise["landline"]?.stringValue
                        param["province_id,city_id,county_id"] = "\(enterprise["areaInformation"]!.dictionaryValue["province_id"]!.stringValue),\(enterprise["areaInformation"]!.dictionaryValue["city_id"]!.stringValue),\(enterprise["areaInformation"]!.dictionaryValue["county_id"]!.stringValue)&\(enterprise["area_name"]!.stringValue)"
                        param["address"] = enterprise["address"]?.stringValue
                        param["zip_code"] = enterprise["zip_code"]?.stringValue
                        param["email"] = enterprise["email"]?.stringValue
                        param["fox"] = enterprise["fox"]?.stringValue
                        self.ca_status = enterprise["ca_status"]?.stringValue ?? "1"
                        self.dicts.forEach({ (d) in
                            let d2 = jsonFormater(data: d)
                            if d2["key"].stringValue == "biz_license_type" {
                                d2["value"].arrayValue.forEach({ (d3) in
                                    if d3["code"].intValue == items["biz_license_type"]!.intValue {
                                        param["biz_license_type"] = "\(items["biz_license_type"]!.stringValue)&\(d3["name"].stringValue)"
                                    }
                                })
                            }
                        })
                        
                        param["biz_license_no"] = items["biz_license_no"]?.stringValue
                        param["biz_license_atta"] = items["biz_license_atta_attachment"]?.dictionaryValue["attachment_token"]?.stringValue
                        param["biz_license_begin_at,biz_license_end_at"] = "\(items["biz_license_begin_at"]!.stringValue),\(items["biz_license_end_at"]!.stringValue)"
                        param["registered_capital"] = items["registered_capital"]?.stringValue
                        param["tax_cert_no"] = items["tax_cert_no"]?.stringValue
                        param["tax_cert_atta"] = items["tax_cert_atta_attachment"]?.dictionaryValue["attachment_token"]?.stringValue
                        param["org_code"] = items["org_code"]?.stringValue
                        param["org_code_atta"] = items["org_code_atta_atta_attachment"]?.dictionaryValue["attachment_token"]?.stringValue
                        param["processing_license_no"] = items["processing_license_no"]?.stringValue
                        param["processing_license_atta"] = items["processing_license_atta_attachment"]?.dictionaryValue["attachment_token"]?.stringValue
                        param["purchase_license_no"] = items["purchase_license_no"]?.stringValue
                        param["purchase_license_atta"] = items["purchase_license_atta_attachment"]?.dictionaryValue["attachment_token"]?.stringValue
                        param["processing_daily_capacity"] = items["processing_daily_capacity"]?.stringValue
                        param["depot_daily_ability"] = items["depot_daily_ability"]?.stringValue
                        self.initData(allData: param)
                    }
                }
            }
        }else if self.type == 1 { // 交易代表
            NetWorkRequest(.daibiaoget()) { (res) -> (Void) in
                if res["code"] as! String == "000000" {
                    let jd = jsonFormater(data: res["data"] as Any)
                    if jd["name"].stringValue.isEmpty == false {
                        param["user_name"] = jd["name"].stringValue
                        param["user_phone"] = jd["phone"].stringValue
                        param["user_auth_letter_atta"] = jd["auth_letter_attachment"].dictionaryValue["attachment_token"]!.stringValue
                        param["user_identity_card"] = jd["identity_card"].stringValue
                        param["user_valid_doc_a_atta,user_valid_doc_b_atta"] = "\(jd["valid_a_doc_attachment"].dictionaryValue["attachment_token"]!.stringValue),\(jd["valid_b_doc_attachment"].dictionaryValue["attachment_token"]!.stringValue)"
                        param["user_code"] = jd["user_code"].stringValue
                        param["user_email"] = jd["email"].stringValue
                        param["user_landline"] = jd["landline"].stringValue
                        param["user_remark"] = jd["remark"].stringValue
                        self.initData(allData: param)
                    }
                }
            }
        }else if self.type == 2{//银行账号信息
            NetWorkRequest(.bankaccget()) { (res) -> (Void) in
                if res["code"] as! String == "000000" {
                    let jd = jsonFormater(data: res["data"] as Any)
                    
                    if jd["bank_id"].stringValue.isEmpty == false {
                        param["bank_id"] = "\(jd["bank_id"].stringValue)&\(jd["bank_name"].stringValue)"
                        param["bank_completely_id"] = "\(jd["bank_completely_id"].stringValue)&\(jd["bank_completely_name"].stringValue)"
                        
                        var ds:[String] = [String]()
                        
                        jd["bank_attachments"].arrayValue.forEach({ (d) in
                            ds.append(d["attachment_token"].stringValue)
                        })
                        
                        param["bank_attachments"] = ds.joined(separator: ",")
                        
                        param["user_identity_card"] = jd["identity_card"].stringValue
                        
                        let areaInformation = jd["areaInformation"].dictionaryValue
                        
                        param["bank_province_id,bank_city_id,bank_county_id"] = "\(areaInformation["province_id"]!.stringValue),\(areaInformation["city_id"]!.stringValue),\(areaInformation["county_id"]!.stringValue)&\(areaInformation["province_name"]!.stringValue),\(areaInformation["city_name"]!.stringValue),\(areaInformation["county_name"]!.stringValue)"
                        param["bank_name"] = jd["account_name"].stringValue
                        param["bank_account"] = jd["bank_account"].stringValue
                        param["bank_account_confirmation"] = jd["bank_account"].stringValue
                        
                        self.initData(allData: param)
                    }
                }
            }
        }else {
            self.navigationItem.rightBarButtonItem = UIBarButtonItem()
        }
    }
    
    
    /// 初始化整体的数据，降低代码耦合
    ///
    /// - Parameter allData: 传入由服务器返回来的参数
    func initData(allData:[String:String]) -> Void {
        
        for i in 0 ..< datas.count {
            var da = datas[i]
            
            for j in 0 ..< da.count {
                var d = da[j]
                
                let key = d["key"] as! String
                let value = allData[key] ?? ""
                if value.isEmpty {
                    continue
                }
                if key.contains("city_id") || key == "bank_completely_id" || key == "bank_id" || key == "biz_license_type" || key == "type" {

                    let vas = value.split(separator: "&")
                    
                    d["value"] = "\(vas[0])"
                    d["subTitle"] = "\(vas[1])"

                    if key == "type" {
                        self.changeRequie("type", String(vas[1]))
                    }
                    
                }else {
                    if d["key"] as! String == "business_type" {
                        self.changeRequie("business_type", allData["business_type"] ?? "")
                    }
                    d["value"] = value
                }
                
                da[j] = d
            }
            
            datas[i] = da
        }
        if datas.count > 3 {
            data1 = datas[3]
            
            if allData["biz_license_type"] == "1" {
                data1 = datas[3]
    //            datas[3]
            }else {
                data2 = datas[3]
                data2.removeSubrange(1...4)
                datas[3] = data2
                self.routerData(newd: ["key":"biz_license_type","value":allData["biz_license_type"] ?? ""])
            }
        }
        
//        print(jsonFormater(data: datas).description)
        self.tableView.reloadData()
    }
    
    func routerData(newd:[String:String]) -> Void {
        for i in 0 ..< datas.count {
            
            var da = datas[i]
            
            var isChange:Bool = false
            
            for j in 0 ..< da.count {
                var d = da[j]
                if newd["key"] == d["key"] as? String {
                    
                    let key = newd["key"]!
                    
                    let value = newd["value"]!
                    
                    if key.contains("city_id") || key == "bank_completely_id" || key == "bank_id" || key == "biz_license_type" || key == "type" {
                        
                        let vas = value.split(separator: "&")
                        if vas.count < 2 {
                            continue
                        }
                        if d["key"] as? String == "biz_license_type" {//营业执照类型
                            for k in 0 ..< da.count {
                                var nd = da[k]
                                if String(vas[0]) == "1" {
                                    datas[3] = data1
                                    nd["title"] = jsonFormater(data:nd["title"] as Any).stringValue.replacingOccurrences(of: "统一社会代码", with: "营业执照")
                                }else {
                                    datas[3] = data2
                                    nd["title"] = jsonFormater(data:nd["title"]!).stringValue.replacingOccurrences(of: "营业执照", with: "统一社会代码")
                                }
                                da[k] = nd
                            }
                        }
                        
                        if key == "type" {
                            self.changeRequie("type", String(vas[1]))
                        }
                        
                        
                        
                        d["value"] = "\(vas[0])"
                        d["subTitle"] = "\(vas[1])"
                        
                        
                    }else {
                        if key == "business_type" {
                            self.changeRequie("business_type", newd["value"]!)
                        }
                        d["value"] = newd["value"]
                    }
                    da[j] = d
                    isChange = true
                    break
                }
            }
            if isChange {
                datas[i] = da
            }
        }
        self.tableView.reloadData()
    }
    
    
    func changeRequie(_ key:String,_ value:String) -> Void {
        if key == "business_type" {
            
            var arr = datas[3]
            var arr2 = datas[4]
            arr[arr.count - 1]["isRequird"] = false
            arr[arr.count - 2]["isRequird"] = false
            arr[arr.count - 3]["isRequird"] = false
            arr[arr.count - 4]["isRequird"] = false
            
            data1[data1.count - 1]["isRequird"] = false
            data1[data1.count - 2]["isRequird"] = false
            data1[data1.count - 3]["isRequird"] = false
            data1[data1.count - 4]["isRequird"] = false
            
            data2[data2.count - 1]["isRequird"] = false
            data2[data2.count - 2]["isRequird"] = false
            data2[data2.count - 3]["isRequird"] = false
            data2[data2.count - 4]["isRequird"] = false
            
            
            arr2[0]["isRequird"] = false
            self.business_types1.forEach { (s) in
                if value.contains(s) {
                    arr[arr.count - 3]["isRequird"] = true
                    arr[arr.count - 4]["isRequird"] = true
                    data1[data1.count - 3]["isRequird"] = true
                    data1[data1.count - 4]["isRequird"] = true
                    data2[data2.count - 3]["isRequird"] = true
                    data2[data2.count - 4]["isRequird"] = true
                    
                    arr2[0]["isRequird"] = true
                    
                }
            }
            
            self.business_types2.forEach { (s) in
                if value.contains(s) {
                    arr[arr.count - 1]["isRequird"] = true
                    arr[arr.count - 2]["isRequird"] = true
                    data1[data1.count - 1]["isRequird"] = true
                    data1[data1.count - 2]["isRequird"] = true
                    data2[data2.count - 1]["isRequird"] = true
                    data2[data2.count - 2]["isRequird"] = true
                }
            }
            datas[4] = arr2
            datas[3] = arr
        }else if key == "type" {
            
            var arr = datas[2]
            var arr2 = datas[3]
            
            arr2[0]["isRequird"] = false
            data1[0]["isRequird"] = false
            data1[1]["isRequird"] = false
            data1[2]["isRequird"] = false
            data1[3]["isRequird"] = false
            data1[4]["isRequird"] = false
            data2[0]["isRequird"] = false
            if arr2.count > 5 {
                arr2[1]["isRequird"] = false
                arr2[2]["isRequird"] = false
                arr2[3]["isRequird"] = false
                arr2[4]["isRequird"] = false
            }
            
            arr[0]["isRequird"] = false
            arr[1]["isRequird"] = false
            arr[2]["isRequird"] = false
            arr[3]["isRequird"] = false
            
            self.types.forEach { (s) in
                if value == s {
                    arr[0]["isRequird"] = true
                    arr[1]["isRequird"] = true
                    arr[2]["isRequird"] = true
                    arr[3]["isRequird"] = true
                    
                    arr2[0]["isRequird"] = true
                    data1[0]["isRequird"] = true
                    data1[1]["isRequird"] = true
                    data1[2]["isRequird"] = true
                    data1[3]["isRequird"] = true
                    data1[4]["isRequird"] = true
                    data2[0]["isRequird"] = true
                    if arr2.count > 5 {
                        arr2[1]["isRequird"] = true
                        arr2[2]["isRequird"] = true
                        arr2[3]["isRequird"] = true
                        arr2[4]["isRequird"] = true
                    }
                    return
                }
            }
            datas[2] = arr
            datas[3] = arr2
        }
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 12
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return datas.count
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return datas[section].count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "UserBase2TableViewCell", for: indexPath) as! UserBase2TableViewCell
        cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
        cell.selectionStyle = UITableViewCellSelectionStyle.none
        
        let data = jsonFormater(data:datas[indexPath.section][indexPath.row])
        
        cell.labelTitle.text = data["title"].stringValue
        let key = data["key"].stringValue
        if data["value"].stringValue.isEmpty {
            cell.labelSubTitle.text = data["subTitle"].stringValue
        }else {
            if data["subTitle"].stringValue == "未上传" {
                cell.labelSubTitle.text = "已上传"
            }else {

                if key.contains("city_id") || key == "type" || key == "biz_license_type"
                    || key == "bank_id" || key == "bank_completely_id" {
                    cell.labelSubTitle.text = data["subTitle"].stringValue
                }else {
                    cell.labelSubTitle.text = data["value"].stringValue
                }
            }
        }
    
        if data["isRequird"].boolValue {
            cell.labelSubTitle.textColor = UIColor.red
        }else {
            cell.labelSubTitle.textColor = UIColor.gray
        }
        if key == "user_remark" {
            cell.labelSubTitle.text = ""
        }
        cell.contentView.backgroundColor = .white
        cell.backgroundColor = .white
        if (UIApplication.shared.delegate as! AppDelegate).isCa == true  {
            if unclickKeys.contains(key) {
                cell.contentView.backgroundColor = UIColor.groupTableViewBackground
                cell.backgroundColor = UIColor.groupTableViewBackground
            }
        }
        
        if key == "user_phone" {
            cell.contentView.backgroundColor = UIColor.groupTableViewBackground
            cell.backgroundColor = UIColor.groupTableViewBackground
        }
        
        if self.noEdit == true && key == "name" {
            cell.contentView.backgroundColor = UIColor.groupTableViewBackground
            cell.backgroundColor = UIColor.groupTableViewBackground
        }
        
        return cell;
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let data = jsonFormater(data: datas[indexPath.section][indexPath.row])
        
        
        if (UIApplication.shared.delegate as! AppDelegate).isCa == true {
            if unclickKeys.contains(data["key"].stringValue) {
                return
            }
        }
        
        if self.noEdit == true && data["key"].stringValue == "name" {
            return
        }
        if data["key"].stringValue == "user_phone" {
            return
        }
        
        if data["type"].intValue == 0 {
            let vc = InputViewController()
            vc.data = datas[indexPath.section][indexPath.row] 
            vc.title = data["title"].stringValue
            
            vc.bl = { (res) -> Void in
                self.routerData(newd: res)
            }
            self.navigationController?.pushViewController(vc, animated: true)
        }else if data["type"].intValue == 1 {//选择，城市选择与其他选择都在这里
            
            
            if data["key"].stringValue.contains("city_id") {//选择城市
//                showMessage(message: "城市")
//                self.cityPicker.sette
                
                if city1.isEmpty {
                    loadCity1()
                    return
                }
                
                var name1:[String] = [String]()
                city1.forEach { (res) in
                    name1.append(res["name"].stringValue)
                }
                
                var name2:[String] = [String]()
                city2.forEach { (res) in
                    name2.append(res["name"].stringValue)
                }
                
                var name3:[String] = [String]()
                city3.forEach { (res) in
                    name3.append(res["name"].stringValue)
                }
                
                
                self.cityPicker.textItemsForComponent = [name1,name2,name3]
                
                self.cityPicker.show()
                
                self.cityPicker.callback = { (res2) -> Void in
                    
                    var str1:String = ""
                    var str2:String = ""
                    self.city1.forEach({ (j) in
                        if j["name"].stringValue == res2[0] {
                            str1.append(j["id"].stringValue)
                            str2.append(j["name"].stringValue)
                        }
                    })
                    str1.append(",")
                    str2.append(",")
                    self.city2.forEach({ (j) in
                        if j["name"].stringValue == res2[1] {
                            str1.append(j["id"].stringValue)
                            str2.append(j["name"].stringValue)
                        }
                    })
                    str1.append(",")
                    str2.append(",")
                    self.city3.forEach({ (j) in
                        if j["name"].stringValue == res2[2] {
                            str1.append(j["id"].stringValue)
                            str2.append(j["name"].stringValue)
                        }
                    })
                    self.routerData(newd: ["key":data["key"].stringValue,"value":"\(str1)&\(str2)"])
                    
                }
                
                self.cityPicker.changeback = { (row,com) -> Void in
                    if com == 0 {//选择城市
                        self.loadCity2(id: self.city1[row]["id"].stringValue)
                    } else if com == 1 {//选择区
                        self.loadCity3(id: self.city2[row]["id"].stringValue)
                    }
                    
                }
                
                
//                self.cityPicker.selectedTitles([data["subTitle"].stringValue], animated: false)
                
                
                
                
            }else if data["key"].stringValue == "biz_license_begin_at,biz_license_end_at" {//日期
                self.showDatePicker(key: data["key"].stringValue, value: "")
            }else {
                
                if data["key"].stringValue == "bank_id" {//开户行
                    NetWorkRequest(.bank()) { (res) -> (Void) in
                        if res["code"] as! String == "000000" {
                            
                            var titles = [String]()
                            
                            jsonFormater(data: res)["data"].arrayValue.forEach({ (js) in
                                
                                titles.append(js["bank_name"].stringValue)
                                
                            })
                            
                            let pickerView = TTADataPickerView(title: data["title"].stringValue, type: .text, delegate: nil)
                            pickerView.type = .text
                            pickerView.textItemsForComponent = [titles]
                            pickerView.selectedTitles([data["subTitle"].stringValue], animated: false)
                            pickerView.show()
                            
                            pickerView.callback = { (res2) -> Void in
                                jsonFormater(data: res)["data"].arrayValue.forEach({ (js) in
                                    
                                    if js["bank_name"].stringValue == res2[0] {
                                        self.routerData(newd: ["key":data["key"].stringValue,"value":"\(js["id"].stringValue)&\(js["bank_name"].stringValue)"])
                                    }
                                    
                                })
                            }
                            
                        }
                    }
                }else if data["key"].stringValue == "bank_completely_id" {//开户行全称
                    
                    let fir = jsonFormater(data: datas[0][0])
                    
                    if fir["value"].stringValue.isEmpty {
                        showMessage(message: "请先选择开户行")
                    }else {
                    
                        NetWorkRequest(.bankReal(id: fir["value"].stringValue)) { (res) -> (Void) in
                            if res["code"] as! String == "000000" {
                                
                                var titles = [String]()
                                
                                let bankd = jsonFormater(data: res["data"] as Any)
                                
                                bankd["data"].arrayValue.forEach({ (js) in
                                    
                                    titles.append(js["bank_name"].stringValue)
                                    
                                })
                                
                                let pickerView = TTADataPickerView(title: data["title"].stringValue, type: .text, delegate: nil)
                                pickerView.type = .text
                                pickerView.textItemsForComponent = [titles]
                                pickerView.selectedTitles([data["subTitle"].stringValue], animated: false)
                                pickerView.show()
                                
                                pickerView.callback = { (res) -> Void in
                                    bankd["data"].arrayValue.forEach({ (js) in
                                        
                                        if js["bank_name"].stringValue == res[0] {
                                            self.routerData(newd: ["key":data["key"].stringValue,"value":"\(js["id"].stringValue)&\(js["bank_name"].stringValue)"])
                                        }
                                        
                                    })
                                }
                                
                            }
                        }
                    }
                }else {
                    var key = data["key"].stringValue
                    if key == "business_type" {
                        key = "biz_type"
                    }
                    dicts.forEach { (res) in
                        if jsonFormater(data: res)["key"].stringValue == key {
                            
                            print(jsonFormater(data: res)["value"].description)
                            
                            var titles = [String]()
                            
                            jsonFormater(data: res)["value"].arrayValue.forEach({ (js) in
                                
                                titles.append(js["name"].stringValue)
                                
                            })
                            
                            let pickerView = TTADataPickerView(title: data["title"].stringValue, type: .text, delegate: nil)
                            pickerView.type = .text
                            pickerView.textItemsForComponent = [titles]
                            pickerView.selectedTitles([data["subTitle"].stringValue], animated: false)
                            pickerView.show()
                            
                            pickerView.callback = { (res2) -> Void in
                                jsonFormater(data: res)["value"].arrayValue.forEach({ (js) in
                                    
                                    if js["name"].stringValue == res2[0] {
                                        self.routerData(newd: ["key":data["key"].stringValue,"value":"\(js["code"].stringValue)&\(js["name"].stringValue)"])
                                    }
                                    
                                })
                            }
                            
                        }
                    }
                }
            }
            
            
        }else if data["type"].intValue == 2 {//多选
            
            self.dicts.forEach({ (dic) in
                let jd2 = jsonFormater(data: dic)
                if jd2["key"].stringValue == "biz_type" {
                    let vc = TagsViewController()
                    vc.data = datas[indexPath.section][indexPath.row]
                    vc.routerData = jd2["value"].arrayObject as! [[String : Any]]
                    vc.title = data["title"].stringValue
                    vc.bl = { (res) -> Void in
                        self.routerData(newd: res)
                    }
                    self.navigationController?.pushViewController(vc, animated: true)
                }
            })
        }else if data["type"].intValue == 3 {
            let vc = R.storyboard.user.idCardViewController()!
            vc.data = datas[indexPath.section][indexPath.row]
            vc.title = data["title"].stringValue
            
            vc.bl = { (res) -> Void in
                self.routerData(newd: res)
            }
            self.navigationController?.pushViewController(vc, animated: true)
        }else if data["type"].intValue == 4 {
           let vc =  UploadImageViewController()
            vc.data = datas[indexPath.section][indexPath.row]
            vc.title = data["title"].stringValue
            
            vc.bl = { (res) -> Void in
                self.routerData(newd: res)
            }
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    
    func showDatePicker(key:String,value:String) -> Void {
        let pic = PGDatePickManager.init()
        pic.datePicker.datePickerMode = .date
        if value.isEmpty {
            
            pic.titleLabel.text = "有效期开始时间"
            pic.datePicker.selectedDate = { (dateComponents)->Void in
                let date = NSCalendar.init(calendarIdentifier: .gregorian)?.date(from: dateComponents!)
                let dateFormate = DateFormatter()
                dateFormate.dateFormat = "yyyy-MM-dd"
                let str = dateFormate.string(from: date!)
                self.showDatePicker(key: key, value: str)
            }
            self.present(pic, animated: false) {
                
            }
        }else {
            
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                pic.titleLabel.text = "有效期结束时间"
                pic.datePicker.selectedDate = { (dateComponents)->Void in
                    let date = NSCalendar.init(calendarIdentifier: .gregorian)?.date(from: dateComponents!)
                    let dateFormate = DateFormatter()
                    dateFormate.dateFormat = "yyyy-MM-dd"
                    let str = dateFormate.string(from: date!)
                    self.routerData(newd: ["key":key,"value":"\(value),\(str)"])
                }
                self.present(pic, animated: false) {
                    
                }
            }
            
            
        }
        
        
    }
    
    
    
    func loadCity1() -> Void {
        NetWorkRequest(.city1()) { (res) -> (Void) in
            if res["code"] as! String == "000000" {
                self.city1 = jsonFormater(data: res as Any)["data"].arrayValue
                self.loadCity2(id: jsonFormater(data:self.city1.first as Any)["id"].stringValue)
            }
        }
    }
    
    func loadCity2(id:String) -> Void {
        NetWorkRequest(.city2(id: id)) { (res) -> (Void) in
            if res["code"] as! String == "000000" {
                self.city2 = jsonFormater(data: res as Any)["data"].arrayValue
                self.loadCity3(id: jsonFormater(data:self.city2.first as Any)["id"].stringValue)
            }
        }
    }
    func loadCity3(id:String) -> Void {
        NetWorkRequest(.city3(id: id)) { (res) -> (Void) in
            if res["code"] as! String == "000000" {
                self.city3 = jsonFormater(data: res as Any)["data"].arrayValue
                
                var name1:[String] = [String]()
                self.city1.forEach { (res) in
                    name1.append(res["name"].stringValue)
                }
                
                var name2:[String] = [String]()
                self.city2.forEach { (res) in
                    name2.append(res["name"].stringValue)
                }
                
                var name3:[String] = [String]()
                self.city3.forEach { (res) in
                    name3.append(res["name"].stringValue)
                }
                
                
                self.cityPicker.textItemsForComponent = [name1,name2,name3]
                
            }
        }
    }
    
    
}
